﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using Domain.Algorithms;

#endregion

namespace Domain {
    public static class Graham {
        public static Graph<HyperEdge> BuildReducedGraph(Graph<HyperEdge> graph) {
            var reducedGraph = new Graph<HyperEdge>(graph);

            var hasEliminationOccured = true;

            while (hasEliminationOccured) {
                hasEliminationOccured = false;

                EliminateLeavesAndIsolatedVertices(reducedGraph, ref hasEliminationOccured);

                EliminateDuplicateEdges(reducedGraph, ref hasEliminationOccured);
                EliminateNakedEdges(reducedGraph, ref hasEliminationOccured);
            }

            return reducedGraph;
        }

        private static void EliminateNakedEdges(Graph<HyperEdge> reducedGraph, ref bool hasEliminationOccured) {
            var edges = new HyperEdge[reducedGraph.Edges.Count];
            reducedGraph.Edges.CopyTo(edges);

            foreach (var edge in edges) {
                if (edge.Vertices.Count == 0) {
                    reducedGraph.Remove(edge);
                    hasEliminationOccured = true;
                }
            }
        }

        private static void EliminateDuplicateEdges(Graph<HyperEdge> reducedGraph, ref bool hasEliminationOccured) {
            var edges = new HyperEdge[reducedGraph.Edges.Count];
            reducedGraph.Edges.CopyTo(edges);

            for (var i = 0; i < edges.Length - 1; i++) {
                for (var j = i + 1; j < edges.Length; j++) {
                    var edge1 = edges[i];
                    var edge2 = edges[j];
                    if (IsIncluded(edge1,edge2)) {
                        reducedGraph.Remove(edge1);
                        hasEliminationOccured = true;
                    }
                }
            }
        }

        private static bool IsIncluded(HyperEdge edge1, HyperEdge edge2) {
            return GraphUtils<HyperEdge>.IsIncluded(edge1.Vertices, edge2.Vertices);
        }

        private static void EliminateLeavesAndIsolatedVertices(Graph<HyperEdge> reducedGraph, ref bool hasEliminationOccured) {
            var vertexDegrees = new Dictionary<Vertex, int>();
            foreach (var vertex in reducedGraph.Vertices) {
                vertexDegrees.Add(vertex, 0);
            }
            foreach (var vertex in reducedGraph.Edges.SelectMany(edge => edge.Vertices)) {
                vertexDegrees[vertex]++;
            }

            var vertices = new Vertex[reducedGraph.Vertices.Count];
            reducedGraph.Vertices.CopyTo(vertices);

            foreach (var vertex in vertices) {
                if (vertexDegrees[vertex] == 1) {
                    reducedGraph.Remove(vertex);
                    hasEliminationOccured = true;
                }
            }
        }
    }
}